/*
 * Copyright (c) 2006-2021, RT-Thread Development Team
 *
 * SPDX-License-Identifier: Apache-2.0
 *
 * Change Logs:
 * Date           Author       Notes
 * 2021-07-03     ThinkPad       the first version
 */
#include <ComApp0.h>
#include <rtthread.h>
#include <rtdevice.h>
#include "drv_common.h"
#include <dfs_posix.h>
#include <../utils/cJSON.h>
#include <ConfigInit.h>
#include <ComApp3.h>
#include <ComApp4.h>
#include <ComApp5.h>
#include <dfs_posix.h>


static char* SAMPLE_UART_NAME = "uart5";


/* 用于接收消息的信号量 */
static struct rt_semaphore rx_sem;
static rt_device_t serial;
static struct serial_configure config = RT_SERIAL_CONFIG_DEFAULT;  /* 初始化配置参数 */


static rt_uint8_t s_buf[512] = {0};
static int s_nStartIndex = 0;










static rt_uint16_t getCrc16(rt_uint8_t *buff, rt_uint16_t bufLen)
{
    rt_uint8_t crc_h[256] =  {
        0x00, 0xC1, 0x81, 0x40, 0x01, 0xC0, 0x80, 0x41, 0x01, 0xC0, 0x80, 0x41,
        0x00, 0xC1, 0x81, 0x40, 0x01, 0xC0, 0x80, 0x41, 0x00, 0xC1, 0x81, 0x40,
        0x00, 0xC1, 0x81, 0x40, 0x01, 0xC0, 0x80, 0x41, 0x01, 0xC0, 0x80, 0x41,
        0x00, 0xC1, 0x81, 0x40, 0x00, 0xC1, 0x81, 0x40, 0x01, 0xC0, 0x80, 0x41,
        0x00, 0xC1, 0x81, 0x40, 0x01, 0xC0, 0x80, 0x41, 0x01, 0xC0, 0x80, 0x41,
        0x00, 0xC1, 0x81, 0x40, 0x01, 0xC0, 0x80, 0x41, 0x00, 0xC1, 0x81, 0x40,
        0x00, 0xC1, 0x81, 0x40, 0x01, 0xC0, 0x80, 0x41, 0x00, 0xC1, 0x81, 0x40,
        0x01, 0xC0, 0x80, 0x41, 0x01, 0xC0, 0x80, 0x41, 0x00, 0xC1, 0x81, 0x40,
        0x00, 0xC1, 0x81, 0x40, 0x01, 0xC0, 0x80, 0x41, 0x01, 0xC0, 0x80, 0x41,
        0x00, 0xC1, 0x81, 0x40, 0x01, 0xC0, 0x80, 0x41, 0x00, 0xC1, 0x81, 0x40,
        0x00, 0xC1, 0x81, 0x40, 0x01, 0xC0, 0x80, 0x41, 0x01, 0xC0, 0x80, 0x41,
        0x00, 0xC1, 0x81, 0x40, 0x00, 0xC1, 0x81, 0x40, 0x01, 0xC0, 0x80, 0x41,
        0x00, 0xC1, 0x81, 0x40, 0x01, 0xC0, 0x80, 0x41, 0x01, 0xC0, 0x80, 0x41,
        0x00, 0xC1, 0x81, 0x40, 0x00, 0xC1, 0x81, 0x40, 0x01, 0xC0, 0x80, 0x41,
        0x01, 0xC0, 0x80, 0x41, 0x00, 0xC1, 0x81, 0x40, 0x01, 0xC0, 0x80, 0x41,
        0x00, 0xC1, 0x81, 0x40, 0x00, 0xC1, 0x81, 0x40, 0x01, 0xC0, 0x80, 0x41,
        0x00, 0xC1, 0x81, 0x40, 0x01, 0xC0, 0x80, 0x41, 0x01, 0xC0, 0x80, 0x41,
        0x00, 0xC1, 0x81, 0x40, 0x01, 0xC0, 0x80, 0x41, 0x00, 0xC1, 0x81, 0x40,
        0x00, 0xC1, 0x81, 0x40, 0x01, 0xC0, 0x80, 0x41, 0x01, 0xC0, 0x80, 0x41,
        0x00, 0xC1, 0x81, 0x40, 0x00, 0xC1, 0x81, 0x40, 0x01, 0xC0, 0x80, 0x41,
        0x00, 0xC1, 0x81, 0x40, 0x01, 0xC0, 0x80, 0x41, 0x01, 0xC0, 0x80, 0x41,
        0x00, 0xC1, 0x81, 0x40
    };

    rt_uint8_t crc_l[256] =   {
        0x00, 0xC0, 0xC1, 0x01, 0xC3, 0x03, 0x02, 0xC2, 0xC6, 0x06, 0x07, 0xC7,
        0x05, 0xC5, 0xC4, 0x04, 0xCC, 0x0C, 0x0D, 0xCD, 0x0F, 0xCF, 0xCE, 0x0E,
        0x0A, 0xCA, 0xCB, 0x0B, 0xC9, 0x09, 0x08, 0xC8, 0xD8, 0x18, 0x19, 0xD9,
        0x1B, 0xDB, 0xDA, 0x1A, 0x1E, 0xDE, 0xDF, 0x1F, 0xDD, 0x1D, 0x1C, 0xDC,
        0x14, 0xD4, 0xD5, 0x15, 0xD7, 0x17, 0x16, 0xD6, 0xD2, 0x12, 0x13, 0xD3,
        0x11, 0xD1, 0xD0, 0x10, 0xF0, 0x30, 0x31, 0xF1, 0x33, 0xF3, 0xF2, 0x32,
        0x36, 0xF6, 0xF7, 0x37, 0xF5, 0x35, 0x34, 0xF4, 0x3C, 0xFC, 0xFD, 0x3D,
        0xFF, 0x3F, 0x3E, 0xFE, 0xFA, 0x3A, 0x3B, 0xFB, 0x39, 0xF9, 0xF8, 0x38,
        0x28, 0xE8, 0xE9, 0x29, 0xEB, 0x2B, 0x2A, 0xEA, 0xEE, 0x2E, 0x2F, 0xEF,
        0x2D, 0xED, 0xEC, 0x2C, 0xE4, 0x24, 0x25, 0xE5, 0x27, 0xE7, 0xE6, 0x26,
        0x22, 0xE2, 0xE3, 0x23, 0xE1, 0x21, 0x20, 0xE0, 0xA0, 0x60, 0x61, 0xA1,
        0x63, 0xA3, 0xA2, 0x62, 0x66, 0xA6, 0xA7, 0x67, 0xA5, 0x65, 0x64, 0xA4,
        0x6C, 0xAC, 0xAD, 0x6D, 0xAF, 0x6F, 0x6E, 0xAE, 0xAA, 0x6A, 0x6B, 0xAB,
        0x69, 0xA9, 0xA8, 0x68, 0x78, 0xB8, 0xB9, 0x79, 0xBB, 0x7B, 0x7A, 0xBA,
        0xBE, 0x7E, 0x7F, 0xBF, 0x7D, 0xBD, 0xBC, 0x7C, 0xB4, 0x74, 0x75, 0xB5,
        0x77, 0xB7, 0xB6, 0x76, 0x72, 0xB2, 0xB3, 0x73, 0xB1, 0x71, 0x70, 0xB0,
        0x50, 0x90, 0x91, 0x51, 0x93, 0x53, 0x52, 0x92, 0x96, 0x56, 0x57, 0x97,
        0x55, 0x95, 0x94, 0x54, 0x9C, 0x5C, 0x5D, 0x9D, 0x5F, 0x9F, 0x9E, 0x5E,
        0x5A, 0x9A, 0x9B, 0x5B, 0x99, 0x59, 0x58, 0x98, 0x88, 0x48, 0x49, 0x89,
        0x4B, 0x8B, 0x8A, 0x4A, 0x4E, 0x8E, 0x8F, 0x4F, 0x8D, 0x4D, 0x4C, 0x8C,
        0x44, 0x84, 0x85, 0x45, 0x87, 0x47, 0x46, 0x86, 0x82, 0x42, 0x43, 0x83,
        0x41, 0x81, 0x80, 0x40
    };


    rt_uint16_t CRCHi = 0xFF;
    rt_uint16_t CRCLo = 0xFF;
    int iIndex = 0;


    for (int i = 0; i < bufLen; i++ )
    {
        iIndex = CRCLo ^ (buff[i]);
        CRCLo = (rt_uint8_t)(CRCHi ^ crc_h[iIndex]);
        CRCHi = crc_l[iIndex];
    }

    return ( CRCLo << 8 | CRCHi );
}




/// 实现一个协议  01 开/关  继电器
/// 01 01 01/00  crc8
/// 02 01 01 04  获取串口配置
/// 7e 7e funCode dataLenH dataLenL data crc16H crc16L 16
///
/// nFunCode: 1, read comSetting
/// nFunCode: 2, read sd space
/// nFunCode: 3, set comSetting

/* 接收数据回调函数 */
static rt_err_t uart_input(rt_device_t dev, rt_size_t size)
{
    /* 串口接收到数据后产生中断，调用此回调函数，然后发送接收信号量 */
    rt_sem_release(&rx_sem);

    return RT_EOK;
}

static void process()
{
    if (s_nStartIndex < 8)
    {
        return;
    }


    int nStartTmp = 0;
    while (nStartTmp+8 <= s_nStartIndex)
    {
        if (s_buf[nStartTmp] != 0x7e && s_buf[nStartTmp+1] != 0x7e)
        {
            nStartTmp += 1;
            continue;
        }

        rt_uint16_t nDataLenGet = s_buf[nStartTmp+3]*256 + s_buf[nStartTmp+4];

        rt_kprintf("nDtaLenGet: %d\n", nDataLenGet);

        if (s_nStartIndex < nStartTmp+8+nDataLenGet)
        {
            // data is not ready
            return;
        }

        if (s_buf[nStartTmp+7+nDataLenGet] != 0x16)
        {
            nStartTmp += 1;
            continue;
        }

        rt_uint16_t nCrc16Get = s_buf[nStartTmp+5+nDataLenGet]*256 + s_buf[nStartTmp+5+nDataLenGet+1];

        rt_kprintf("crc16 get: %d\n", nCrc16Get);

        rt_uint16_t nCrc16Cal = getCrc16(s_buf+nStartTmp, 5+nDataLenGet);
        rt_kprintf("crc16 cal: %d\n", nCrc16Cal);

        if (nCrc16Get != nCrc16Cal)
        {
            nStartTmp += 1;
            continue;
        }

        rt_uint8_t nFunCode = s_buf[nStartTmp+2];


        /// nFunCode: 1, read comSetting
        /// nFunCode: 2, read sd space
        /// nFunCode: 3, set comSetting
        if (1 == nFunCode)
        {
            rt_kprintf("\n  receive com setting cmd  \n");

            cJSON * root = getComConfigRoot();
            char* config = cJSON_PrintUnformatted(root);

            rt_uint8_t buff[1024] = {0};
            buff[0] = 0x7e;
            buff[1] = 0x7e;
            buff[2] = 1;
            rt_uint16_t nDataLen = strlen(config);

            rt_kprintf("nDataLen: %d\n", nDataLen);

            buff[3] = nDataLen&0xff;
            buff[4] = (nDataLen&0xff00) >> 8;

            memcpy(buff+5, config, nDataLen);

            rt_uint16_t nCrc16 = getCrc16(buff, nDataLen+5);
            buff[nDataLen+5] = (nCrc16&0xff00) >> 8;
            buff[nDataLen+6] = nCrc16&0xff;
            buff[nDataLen+7] = 0x16;


            rt_device_write(serial, 0, buff, nDataLen+8);
//                rt_device_write(serial, 0, config, nDataLen);
        }

        else if (2 == nFunCode)
        {
            rt_kprintf("funCode is 22\n");
//            int dfs_statfs(const char *path, struct statfs *buffer)
            struct statfs sdInfo;
            if (0 == dfs_statfs("/", &sdInfo))
            {
                rt_kprintf("free block: %d\n", sdInfo.f_bfree);
                rt_kprintf("total block: %d\n", sdInfo.f_blocks);
                rt_kprintf("block size: %d\n", sdInfo.f_bsize);

                cJSON *sdInfoJson = cJSON_CreateObject();
                cJSON_AddNumberToObject(sdInfoJson, "freeBlock", sdInfo.f_bfree);
                cJSON_AddNumberToObject(sdInfoJson, "totalBlock", sdInfo.f_blocks);
                cJSON_AddNumberToObject(sdInfoJson, "blockSize", sdInfo.f_bsize);

                char* sdInfoC = cJSON_PrintUnformatted(sdInfoJson);

                rt_uint8_t buff[128] = {0};
                buff[0] = 0x7e;
                buff[1] = 0x7e;
                buff[2] = 2;
                rt_uint16_t nDataLen = strlen(sdInfoC);

                buff[3] = nDataLen&0xff;
                buff[4] = (nDataLen&0xff00) >> 8;

                memcpy(buff+5, sdInfoC, nDataLen);

                rt_uint16_t nCrc16 = getCrc16(buff, nDataLen+5);
                buff[nDataLen+5] = (nCrc16&0xff00) >> 8;
                buff[nDataLen+6] = nCrc16&0xff;
                buff[nDataLen+7] = 0x16;
                rt_device_write(serial, 0, buff, nDataLen+8);
            }
            else {
                rt_kprintf("get sd info failed\n");
            }
        }

        // nFunCode: 3, set comSetting
        else if (3 == nFunCode)
        {
            memset(s_buf+nStartTmp+5+nDataLenGet, 0, 512-(nStartTmp+5+nDataLenGet));
            cJSON *oneComInfo = cJSON_Parse(s_buf+5+nStartTmp);
            int nIndex = cJSON_GetObjectItem(oneComInfo, "ind")->valueint;
            rt_kprintf("\n");
            rt_kprintf("nIndex: %d\n", nIndex);

            cJSON * root = getComConfigRoot();
            cJSON_ReplaceItemInArray(root, nIndex, oneComInfo);
            updateFile(root);

            if (0 == nIndex)
            {
                restartComApp1();
                restartDataConverge();
            }
            else if (1 == nIndex)
            {
                restartComApp2();
            }
            else if (nIndex == 2)
            {
                restartComApp3();
            }
            else if (nIndex == 3)
            {
                restartComApp4();
            }
            else if (nIndex == 4)
            {
                restartComApp5();
            }
        }

        /// remove all the data(except config file), and mkdir serial_data and udp_data
        else if (4 == nFunCode)
        {
            if (0 == access("/serial_data", 0))  // if exists the dir, delete it
            {
                rmdir("/serial_data");
            }

            if (0 == access("udp_data", 0)) // if exists the dir, delete it
            {
                rmdir("/udp_data");
            }
        }

        /// sync time
        else if (5 == nFunCode)
        {
            rt_uint8_t y = s_buf[nStartTmp+5];
            rt_uint8_t M = s_buf[nStartTmp+6];
            rt_uint8_t d = s_buf[nStartTmp+7];
            rt_uint8_t h = s_buf[nStartTmp+8];
            rt_uint8_t m = s_buf[nStartTmp+9];
            rt_uint8_t s = s_buf[nStartTmp+10];

            set_date(y+2000, M, d);
            set_time(h, m, s);
        }

        s_nStartIndex = 0;
    }
}

static void serial_thread_entry(void *parameter)
{
    rt_uint8_t ch;
    //char str[] = "hello\r\n";

    while (1)
    {
        /* 从串口读取一个字节的数据，没有读取到则等待接收信号量 */
        while (rt_device_read(serial, -1, &ch, 1) != 1)
        {
            /* 阻塞等待接收信号量，等到信号量后再次读取数据 */
            rt_sem_take(&rx_sem, RT_WAITING_FOREVER);
        }

//        if (ch == 'o')
//        {
//            BoardRelay_Open(1);
//        }
//        else if (ch == 'c')
//        {
//            BoardRelay_Close(1);
//        }

        /* 读取到的数据通过串口错位输出 */
//        ch = ch + 2;
//        rt_device_write(serial, 0, &ch, 1);
//        rt_device_write(serial, 0, str, (sizeof(str) - 1));
//        rt_thread_mdelay(200);


//        rt_kprintf("%x ", ch);

        s_buf[s_nStartIndex++] = ch;
        process();

    }
}



int ComApp0()
{
    rt_err_t ret = RT_EOK;
    char uart_name[RT_NAME_MAX];
    char str[] = "hello RT-Thread!\r\n";

    rt_strncpy(uart_name, SAMPLE_UART_NAME, RT_NAME_MAX);

    /* step1：查找串口设备 */
    serial = rt_device_find(uart_name);

    if (RT_NULL == serial)
    {
        rt_kprintf("\nopen com0 failed\n");
    }
    else {
        rt_kprintf("\nopen com0 ok\n");
    }

    /* step2：修改串口配置参数 */
    config.baud_rate = BAUD_RATE_9600;      //修改波特率为 9600
    config.data_bits = DATA_BITS_8;           //数据位 8
    config.stop_bits = STOP_BITS_1;           //停止位 1
    config.rx_bufsz  = 512;                   //修改缓冲区 buff size 为 128
    config.parity    = PARITY_NONE;           //无奇偶校验位

    /* step3：控制串口设备。通过控制接口传入命令控制字，与控制参数 */
    rt_device_control(serial, RT_DEVICE_CTRL_CONFIG, &config);

    /* 初始化信号量 */
    rt_sem_init(&rx_sem, "rx_sem", 0, RT_IPC_FLAG_FIFO);
    /* 以中断接收及轮询发送模式打开串口设备 */
    rt_device_open(serial, RT_DEVICE_FLAG_TX_BLOCKING|RT_DEVICE_FLAG_RX_NON_BLOCKING);
    /* 设置接收回调函数 */
    rt_device_set_rx_indicate(serial, uart_input);
    /* 发送字符串 */
    rt_device_write(serial, 0, str, (sizeof(str) - 1));

    /* 创建 serial 线程 */
    rt_thread_t thread = rt_thread_create("tCom0", serial_thread_entry, RT_NULL, 4096, 25, 10);
    /* 创建成功则启动线程 */
    if (thread != RT_NULL)
    {
        rt_kprintf("start com0 thread ok\n");
        rt_thread_startup(thread);
    }
    else
    {
        rt_kprintf("start com0 thread failed\n");
        ret = RT_ERROR;
    }


    return ret;
}


